package net.esj.basic.core.view.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.esj.basic.utils.Validators;
import net.esj.basic.utils.view.URIUtils;

public class BackUrlFilter implements Filter {

	public static final String BACK_URL = "_BACK_URL";//SESSION回转地址存放
	
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		String uri = request.getRequestURI();
		String method = request.getMethod();
		Map parameters = request.getParameterMap();
		BackUri back = (BackUri) request.getSession().getAttribute(BACK_URL);
		if(back == null){
			back = new BackUri();
		}
		back.setMethod(method);
		back.setUri(uri);
		back.setQueryStr(request.getQueryString());
		request.getSession().setAttribute(BACK_URL,back);
		arg2.doFilter(arg0, arg1);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

	public static class BackUri{
		private String method;
		private String uri;
		private String queryStr;
		
		public String getMethod() {
			return method;
		}
		public void setMethod(String method) {
			this.method = method;
		}
		public String getUri() {
			return uri;
		}
		public void setUri(String uri) {
			this.uri = uri;
		}
		
		public String getQueryStr() {
			return queryStr;
		}
		public void setQueryStr(String queryStr) {
			this.queryStr = queryStr;
		}
		public String getBackURI(){
			if(!Validators.isEmpty(queryStr)){
				return uri+"?"+queryStr;
			}
			return uri;
		}
		
	}
	
}
